<?php

class Cas extends BaseCas
{
    public function __toString()
    {
        return mb_substr($this->getOpis(), 0, 20, 'UTF-8');
    }

    public function save(PropelPDO $con = null)
    {
        $old = $this->getId();

        $max_date = DbFinder::from('Cas')->withColumn('max(Cas.Datum)', 'maxDatum')->withColumn('max(Cas.RedBr)', 'maxRedBr')->withColumn('count(Cas.Id)', 'brCasova')->select(array('maxDatum', 'maxRedBr', 'brCasova'))->where('RazredId', $this->getRazredId())->where('PredmetId', $this->getPredmetId())->findOne();
        parent::save();

        if(($this->getDatum() < $max_date['maxDatum']) or ($old) or ($max_date['brCasova'] < $max_date['maxRedBr']))
        {
          $this->orderRedBrs();
        }

        else
        {
          if(!$old)
            $this->setRedBr($max_date['maxRedBr'] + 1);
          parent::save();
        }
    }

    private function orderRedBrs()
    {
        $cass = DbFinder::from('Cas')->where('RazredId', $this->getRazredId())->where('PredmetId', $this->getPredmetId())->orderBy('Datum')->find();
        $i = 1;
        foreach($cass as $cas)
        {
            CasFunctions::updateCas($cas->getId(), $i++);
        }
    }
}

class CasFunctions
{
    public static function updateCas($id, $i)
    {
        DbFinder::from('Cas')->where('Id', $id)->set(array('RedBr' => $i));
    }

}